package com.ruitu.mall_98_2.mine.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyRefreshBaseFragment;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.ScreenUtils;
import com.beanu.arad.utils.SizeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.mine.Collection;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.utils.GlideUtil;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class FragmentCollection extends MyRefreshBaseFragment {
    private DataAdapter adapter;
    private LRecyclerView lRecyclerView;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private List<Integer> skipId = new ArrayList<>();
    private String id;
    private AlertDialog alertDialog;

    public static FragmentCollection newInstance() {
        Bundle args = new Bundle();
        FragmentCollection fragment = new FragmentCollection();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getInflate() {
        return R.layout.fragment_mine_three;
    }

    @Override
    protected LRecyclerView getRecyclerView(View view) {
        lRecyclerView = view.findViewById(R.id.lRecyclerView);
        return lRecyclerView;
    }

    @Override
    protected ProgressLayout findProgressLayout(View view) {
        return view.findViewById(R.id.progress);
    }

    @Override
    protected RecyclerView.Adapter initAdapter() {
        adapter = new DataAdapter(getContext());
        return adapter;
    }

    @Override
    protected void reqFirst() {
        reReq();
    }

    @Override
    protected void reqMore() {

    }

    @Override
    protected void reReq() {
        getCollection();
    }

    @Override
    protected void initRecyclerView(View v) {
        super.initRecyclerView(v);
        lRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, 1));
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lRecyclerView.setAdapter(lRecyclerViewAdapter);
        lRecyclerView.setLoadMoreEnabled(false);
    }

    class DataAdapter extends ListBaseAdapter<Collection> {

        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_commodity;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
//            ImageView icon = holder.getView(R.id.icon);
//            TextView tv_name = holder.getView(R.id.tv_name);
//            TextView tv_price = holder.getView(R.id.tv_price);
//            RelativeLayout rl_item = holder.getView(R.id.rl_item);
//            final Collection collections = mDataList.get(position);
//            Glide.with(mContext).load(Config.BASE_URL + collections.getImageUrl()).apply(Arad.opts).into(icon);
//            tv_name.setText(collections.getGoodName());
//            tv_price.setText("￥" + collections.getGoodMarket());
//            rl_item.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Product product = new Product();
//                    product.setGoodId(collections.getGoodId());
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("product", product);
//                    try {
//                        A_Rutils.startActivity(mContext, "com.ruitu.mall_98_1.product.activity.ProductDetailActivity", bundle);
//                    } catch (ClassNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
//
//            rl_item.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    id = collections.getCollectionId();
//                    showCancleDialog();
//                    return false;
//                }
//            });

            RelativeLayout rl_item = holder.getView(R.id.rl_item);
            ImageView icon = holder.getView(R.id.icon);
            RelativeLayout rl_icon = holder.getView(R.id.rl_icon);//包裹icon的布局
            TextView tv_pro_name = holder.getView(R.id.tv_pro_name);//商品名称
            TextView tv_price = holder.getView(R.id.tv_price);//现价
            TextView tv_price_del = holder.getView(R.id.tv_price_del);//原价
            TextView tv_xiajia = holder.getView(R.id.tv_xiajia);//是否下架
            final Collection pro = mDataList.get(position);

            int width = ScreenUtils.getScreenWidth();
            int itemWidth = (width - (SizeUtils.dp2px(40))) / 2;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_icon.getLayoutParams();
            params.width = itemWidth;
            params.height = itemWidth;
            rl_icon.setLayoutParams(params);

            if (TextUtils.equals("0", pro.getStatus())) {//0 下架 1 在售
                tv_xiajia.setVisibility(View.VISIBLE);
            } else {
                tv_xiajia.setVisibility(View.GONE);
            }

            GlideUtil.loadImg(Config.BASE_URL + pro.getImageUrl(), icon);
            tv_pro_name.setText(pro.getGoodName());
            tv_price.setText("￥" + pro.getGoodMarket());
            tv_price_del.setText("￥" + pro.getOriginalPrice());
            UIUtils.setDelLine(tv_price_del);

            TextView tv_sale_num = holder.getView(R.id.tv_sale_num);//销量
            if (null != tv_sale_num) {
                tv_sale_num.setText("销量" + (pro.getGoodVolume() > 999 ? 999 + "+" : pro.getGoodVolume() + ""));
            }

            rl_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Product product = new Product();
                    product.setGoodId(pro.getGoodId());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("product", product);
                    try {
                        A_Rutils.startActivity(mContext, "com.ruitu.mall_98_1.product.activity.ProductDetailActivity", bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });

            rl_item.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    id = pro.getCollectionId();
                    showCancleDialog();
                    return true;
                }
            });

            //下面是设置标签的,只适用于部分页面
            TextView tag_zidingyi = holder.getView(R.id.tag_zidingyi);//自定义
            TextView tag_pintuan = holder.getView(R.id.tag_pintuan);//拼团
            TextView tag_qujianjia = holder.getView(R.id.tag_qujianjia);//区间价
            TextView tag_yuding = holder.getView(R.id.tag_yuding);//预订
            TextView tag_yushou = holder.getView(R.id.tag_yushou);//预售

            try {
                if (!TextUtils.isEmpty(pro.getGoodTagName())) {//是否有自定义标签
                    tag_zidingyi.setVisibility(View.VISIBLE);
                    tag_zidingyi.setText(pro.getGoodTagName());//设置自定义标签名称
                } else {
                    tag_zidingyi.setVisibility(View.GONE);
                }
            } catch (Exception e) {
            }
            try {
                if (TextUtils.equals("1", pro.getShoppingGroupStatus())) {//是否团购 0 否 1 是
                    tag_pintuan.setVisibility(View.VISIBLE);
                } else {
                    tag_pintuan.setVisibility(View.GONE);
                }
            } catch (Exception e) {
            }
            try {
                if (TextUtils.equals("1", pro.getIntervalStatus())) {//是否区间价格 0 否 1 是
                    tag_qujianjia.setVisibility(View.VISIBLE);
                } else {
                    tag_qujianjia.setVisibility(View.GONE);
                }
            } catch (Exception e) {
            }
            try {
                if (TextUtils.equals("1", pro.getCustomizedStatus())) {//是否预订 0 否 1 是
                    tag_yuding.setVisibility(View.VISIBLE);
                } else {
                    tag_yuding.setVisibility(View.GONE);
                }
            } catch (Exception e) {
            }
            try {
                if (TextUtils.equals("1", pro.getGoodSalesModel())) {//销售模式（1：预售、2：现货)
                    tag_yushou.setVisibility(View.VISIBLE);
                } else {
                    tag_yushou.setVisibility(View.INVISIBLE);
                }
            } catch (Exception e) {
            }

        }
    }

    public void getCollection() {
        showProgress();
        APIRetrofit.getDefault().getCollectionList(AppHolder.instance().getUser().getAccountId(), "1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<List<Collection>>>() {
                    @Override
                    public void onError(Throwable e) {
                        refreshComplete();
                        hideProgress();
                        ToastUtils.showShort("获取收藏列表失败");
                        showError(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                reReq();
                            }
                        });
                    }

                    @Override
                    public void onNext(BaseResult<List<Collection>> baseResult) {
                        refreshComplete();
                        hideProgress();
                        if (baseResult.isSuccess()) {
                            if (isDataEmpty(baseResult.getData())) {
                                showEmptyView(skipId);
                            } else {
                                adapter.setDataList(baseResult.getData());
                                showContent(null);
                            }
                        }
                    }
                });
    }

    private void showCancleDialog() {
        alertDialog = new AlertDialog.Builder(getContext()).create();
        View view = View.inflate(getContext(), R.layout.dialog_cancle_collection, null);
        TextView tv_cancle = view.findViewById(R.id.tv_cancle);
        tv_cancle.setText("取消收藏");
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress();
                cancelCollection();
            }
        });
        alertDialog.setView(view);
        Window window = getActivity().getWindow();
        window.setGravity(Gravity.CENTER);
        alertDialog.show();
    }

    private void cancelCollection() {
        APIRetrofit.getDefault().cancelCollection(id)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        ToastUtils.showLong("取消收藏异常");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        hideProgress();
                        if (baseResult.isSuccess()) {
                            alertDialog.dismiss();
                            ToastUtils.showLong(baseResult.getMsg());
                            reReq();
                        } else {
                            ToastUtils.showLong(baseResult.getMsg());
                        }
                    }
                });
    }
}
